package util;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Util {

	public static Image imagePathToImage(String filePath)
			throws FileNotFoundException, IOException {
		File file = new File(filePath);

		@SuppressWarnings("resource")
		FileInputStream fis = new FileInputStream(file);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buf = new byte[1024];

		for (int readNum; (readNum = fis.read(buf)) != -1;) {
			bos.write(buf, 0, readNum);
		}
		byte[] bytes = bos.toByteArray();

		return new ImageIcon(bytes).getImage();
	}

	public static void showImage(Image image) {
		JFrame frame = new JFrame("Image");
		final JLabel label = new JLabel(new ImageIcon(image));
		frame.getContentPane().add(label);
		frame.setVisible(true);
	}

	public static int[] imageToPixels(Image image) {

		int width = image.getWidth(null);
		int height = image.getHeight(null);
		int pixelsNumber = width * height;
		int pixels[] = new int[pixelsNumber];

		PixelGrabber pg = new PixelGrabber(image, 0, 0, width, height, pixels,
				0, width);

		try {
			pg.grabPixels();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		for (int i = 0; i < pixels.length; i++) {
			// System.out.println(pixels[i]);
			// System.out.println(RGBtoCMYK.convert(pixels[i]));

		}
		return pixels;
	}

	public static void writhImage(Image image, String fileName)
			throws FileNotFoundException, IOException {
		BufferedImage bufferedImage = new BufferedImage(image.getWidth(null),
				image.getHeight(null), BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = bufferedImage.createGraphics();
		g2.drawImage(image, null, null);
		File imageFile = new File(fileName + ".png");
		try {
			ImageIO.write(bufferedImage, "png", imageFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static BufferedImage imageToBufferedImage(Image image) {
		BufferedImage bufferedImage = new BufferedImage(image.getWidth(null),
				image.getHeight(null), BufferedImage.TYPE_INT_BGR);
		bufferedImage.createGraphics().drawImage(image, 0, 0, null);
		return bufferedImage;
	}
}
